<template>
  <div class="himm_line" @mouseup="handleMouseUp">
    <slot></slot>
    <div
      class="himm_line_popup"
      ref="himm_line_popup"
      :style="popupPosition"
      v-if="showPopup"
      @click="handleClick"
    >
      <slot name="popup" :text="text"></slot>
    </div>
  </div>
</template>

<script>
export default {
  mounted() {
    console.log(4111);
  },
  data() {
    return {
      showPopup: false,
      popupPosition: {
        left: 0,
        top: 0,
      },
      text: "",
    };
  },
  methods: {
    async handleMouseUp() {
      console.log(1111);
      let sel = window.getSelection();
      let range = sel.getRangeAt(0);
      //没有选区
      if (range.collapsed) {
        console.log(2222);
        this.closePopup();
        return;
      }
      this.text = range.toString();
      const rect = range.getBoundingClientRect();
      this.updatePopupPosition(rect);
      this.showPopup = true;
      await this.$nextTick();
      document.body.appendChild(this.$refs.himm_line_popup);
    },

    updatePopupPosition(rect) {
      const scrollLeft =
        window.pageXOffset || document.documentElement.scrollLeft;
      this.popupPosition = {
        left: `${rect.left + rect.width / 2 + scrollLeft - 30}px`,
        top: `${rect.bottom}px`,
      };
      console.log(this.popupPosition);
    },
    closePopup(e) {
      if (
        this.$refs.himm_line_popup &&
        this.$refs.himm_line_popup.contains(e.target)
      ) {
        return;
      }
      this.showPopup = false;
      window.getSelection().removeAllRanges();
    },
    handleClick() {
      this.showPopup = false;
      window.getSelection().removeAllRanges();
    },
  },
  watch: {
    showPopup: {
      handler(nv, ov) {
        if (nv) {
          document.addEventListener("mousedown", this.closePopup);
        } else {
          document.removeEventListener("mousedown", this.closePopup);
        }
      },
    },
  },
  beforeDestroy() {
    document.removeEventListener("mousedown", this.closePopup);
  },
};
</script>
<style scoped lang="less">
.himm_line {
  width: 100%;
  height: fit-content;
}
</style>
<style lang="less">
.himm_line_popup {
  position: fixed;
  width: 203px;
  height: 32px;
  background: #ffffff;
  box-shadow: 0px 3px 20px 0px rgba(23, 36, 70, 0.35);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  font-size: 14px;
  line-height: 16px;
  & > div {
    cursor: pointer;
  }
}
</style>
